package com.cole.miniapp.project.notify.controller;

import com.cole.miniapp.common.utils.JsonUtils;
import com.cole.miniapp.project.service.PayService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxScanPayNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 接收微信支付通知
 * 
 * @author cole
 *
 */
@RestController
@RequestMapping("/wx/pay/notify")
public class WxPayNotifyController {
	
	private static final Logger log = LoggerFactory.getLogger(WxPayNotifyController.class);
			
			
	@Autowired
	private WxPayService wxService;

	@Autowired
	private PayService payService;


	/**
	 * 支付回调通知处理
	 * 
	 * @param xmlData
	 * @return
	 * @throws WxPayException
	 */
	@PostMapping("/order")
	public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException, WxErrorException {
		final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(xmlData);
		
		log.info("接收支付回调通知消息："+ JsonUtils.objectToJson(notifyResult));
		// TODO 根据自己业务场景需要构造返回对象

		payService.updateOrder(notifyResult);

		return WxPayNotifyResponse.success("成功");
	}

	/**
	 * 退款回调通知处理
	 * 
	 * @param xmlData
	 * @return
	 * @throws WxPayException
	 */
	@PostMapping("/refund")
	public String parseRefundNotifyResult(@RequestBody String xmlData) throws WxPayException {
		final WxPayRefundNotifyResult result = this.wxService.parseRefundNotifyResult(xmlData);
		
		log.info("接收退款回调通知消息："+ JsonUtils.objectToJson(result));
		
		// TODO 根据自己业务场景需要构造返回对象
		return WxPayNotifyResponse.success("成功");
	}

	/**
	 * 扫码支付回调通知处理
	 * 
	 * @param xmlData
	 * @return
	 * @throws WxPayException
	 */
	@PostMapping("/scanpay")
	public String parseScanPayNotifyResult(String xmlData) throws WxPayException {
		final WxScanPayNotifyResult result = this.wxService.parseScanPayNotifyResult(xmlData);
		
		log.info("接收扫码支付回调通知消息："+ JsonUtils.objectToJson(result));
		
		// TODO 根据自己业务场景需要构造返回对象
		return WxPayNotifyResponse.success("成功");
	}
}
